package controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import entity.JsonMsg;
import entity.School;
import entity.User;
import service.SchoolService;
import service.UserService;
import service.impl.SchoolServiceImpl;
import service.impl.UserServiceImpl;

/**
 * Servlet implementation class RegServlet
 */
//@WebServlet("/RegServlet")
public class RegServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
//    public RegServlet() {
//        super();
//        // TODO Auto-generated constructor stub
//    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");

		// Create a factory for disk-based file items
		DiskFileItemFactory factory = new DiskFileItemFactory();

		// Configure a repository (to ensure a secure temp location is used)
		ServletContext servletContext = this.getServletConfig().getServletContext();
		File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
		factory.setRepository(repository);

		// Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);

		/*
		 * 判断request 的请求方式是否为post并且contentType是否以multipart/开头
		 *
		 * 如果不是说明是普通的表单提交
		 */
		if (!ServletFileUpload.isMultipartContent(request)) {
			return;
		}
		// Parse the request
		try {
			User user = new User();
			SchoolService schoolService = new SchoolServiceImpl();
			List<FileItem> items = upload.parseRequest(request);
			for (FileItem item : items) {

				if (item.isFormField()) {
					String filename = item.getFieldName();
					String value = item.getString("utf-8");
					// System.out.println("form"+filename+":"+value);
					if (filename.equals("username")) {
						user.setUsername(value);
					} else if (filename.equals("password")) {
						user.setPassword(value);
					} else if (filename.equals("email")) {
						user.setEmail(value);
					} else if (filename.equals("sex")) {
						user.setGender(value);
					} else if (filename.equals("name")) {
						user.setRealname(value);
					} else if (filename.equals("id")) {
						user.setStudentid(value);
					} else if (filename.equals("mobile")) {
						user.setPhone(value);
					} else if (filename.equals("register_school")) {
						School school = schoolService.findBySname(value);
						user.setSchool(school);
					}
				} else {
					String filename = item.getName();
					System.out.println("photo filename:" + filename);
					String type = item.getContentType();
					System.out.println("photo type:" + filename);
					if (filename == null || filename.trim().equals("")) {// 如果為空則跳過
						continue;
					}

					String suffix = filename.substring(filename.lastIndexOf("."));//文件后缀名
					System.out.println("photo suffix:" + suffix);
					UUID uuid = UUID.randomUUID(); // 随机生成一个唯一标记
					String prefix = uuid.toString().replace("-", "");
					String savefilename = prefix + suffix;
//									savefilename=savefilename.replace("-", "");
					String path = servletContext.getRealPath("/admin/");

					System.out.println("photo path:" + path);
//					user.setPhoto(path+File.separator+savefilename);
					user.setPhoto(savefilename);
					InputStream is = item.getInputStream();
					OutputStream os = new FileOutputStream(new File(path + File.separator + savefilename));
					byte[] b = new byte[1024];
					int len;
					while ((len = is.read(b)) != -1) {
						os.write(b, 0, len);
					}
					is.close();
					os.close();
				}
			}
			System.out.println("userpwd" + user.getPassword());
			UserService userservice = new UserServiceImpl();
			boolean result = userservice.addUser(user);
			JsonMsg jsonMsg = null;
			if (result) {
				response.sendRedirect("/CampusPT/user/index.jsp");
			} else {
				response.sendRedirect("/CampusPT/user/NewFile.jsp");
			}
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
